import React, { useState,useRef,useEffect } from 'react';
import { Form, Input, Modal, Descriptions, Badge, Button, Divider, Table, Space, Upload, Select,message,Spin } from 'antd';
import Nunberinput from '../../../../components/Nunberinput/Nunberinput'
import { UploadOutlined } from '@ant-design/icons';
import {searchstuList,addstudent,getstudents,studentDel} from '../service'
import Grade from '../../../dashboard/user-list/components/personInfo';
import axios from 'axios'
import { value } from 'numeral';
import ExportJsonExcel from 'js-export-excel';
const { Option } = Select;

const { TextArea } = Input;

const FormItem = Form.Item;

const Personinfo = props => {
  const [teachdata, setteachdata] = useState([])
  const [lastFetchId, setlastFetchId] = useState(0)
  const [classvalue, setclassvalue] = useState('')
  const [classfetch, setclassfetch] = useState(false)
  const [stulist, setstulist] = useState([])
  const [grade, setgrade] = useState('');//修改实验成绩和记录,评价的数据
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);//选择列表
  const [createModalVisible, handleModalVisible] = useState(false);
  const [gradeVisible, setgradeVisible] = useState(false);//成绩查询弹框
  const [gradeCurrent, setgradeCurrent] = useState(null)

  const [form] = Form.useForm();
  const { modalVisible, currentclass, onCancel } = props;
  let query = useRef({
    pageIndex:1,
    pageSize:20,
})
const paginationProps = {
  showSizeChanger: true,
  showQuickJumper: true,
  pageSize: query.current.pageSize,
  total: 0,
  onChange:(pageIndex, pageSize)=>{
      query.current={...query.current,pageIndex, pageSize}
      console.log(query.current)
      getlist(currentclass.id)


  },

    onShowSizeChange:(pageIndex, pageSize)=>{
      query.current={...query.current,pageIndex, pageSize}
      getlist(currentclass.id)

  }
};
  useEffect(() => {
    // 如果有props.current的值才会执行这个
    console.log(currentclass)
    if (currentclass) {
      setgrade(currentclass)
      getlist(currentclass.id)
      console.log(grade)
    }

  }, [props.currentclass]);
  const getlist =async (id)=>{
    const res =await getstudents({...query.current,examId:id})
    setstulist(res.data.list)
    paginationProps.total=res.data.total

  }
  const fetchUser =async value => {
    console.log('fetching user', value);
    setlastFetchId(lastFetchId + 1);
    const fetchId = lastFetchId;
    setteachdata([])
    setclassfetch(true)
   const datas= await searchstuList({name:value})
         if (fetchId !== lastFetchId) {
          // for fetch callback order
          return;
        }
        setteachdata(datas.data)

  
  };
  const handleChange =async value => {
    console.log(value)
    setclassvalue(value)
  };
 
    // 删除
    const deleteItem =async id => {
     const res = await studentDel({id:id})
     getlist(currentclass.id)


   
    };
  const del = (currentItem) => {
      let str=''
      if (currentItem) {
          str=currentItem.id
      }else{
        //字符串拼接
        str=selectedRowKeys.join(',')
      }
      console.log(currentItem,str)

      console.log(str,currentItem)
      Modal.confirm({
          title: '删除任务',
          content: '确定删除该任务吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => deleteItem(str),
        });
  }
 // 查询成绩孙组件成绩信息
const findgrade = async fields => {
  const hide = message.loading('正在查询');
  console.log(1111)
  try {
      var a = await addRule({
          desc: fields.desc,
      });
      console.log(a)
      hide();
      message.success('查询成功');
      return true;
  } catch (error) {
      hide();
      message.error('查询失败请重试！');
      return false;
  }
};

  // 导出成绩excel

  // 班级成员添加
  const showModal = () => {
    handleModalVisible(true)
  };

  const hideModal = () => {
    handleModalVisible(false)
    // 提交id
  };
  const addstu=async ()=>{
    const res = await addstudent({classId:grade.id,id:classvalue})
    hideModal(false)
    getlist(currentclass.id)

  }  // 查看成绩

  // 选择框
  const onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    setSelectedRowKeys(selectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
   //  导出
   const ExportToExcel = () => {
    const data = stulist // 准备的数据
    var option = {}
    let dataTable = []
    data.map(item=>{
      let obj = {
        'VESSEL':item.name,  // '列名': 数据
        'ASN NUMBER': item.student_number,
        'experiment_result':item.experiment_result,
        'teacher_comment':item.teacher_comment,
        'exam_time':item.exam_time,
      }
      dataTable.push(obj);
    })
  
    option.fileName = `${grade.exam_name}成绩单`  //导出的Excel文件名
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: 'sheet',
        sheetFilter: ['VESSEL', 'ASN NUMBER', 'experiment_result','teacher_comment','exam_time'],
        sheetHeader: ['学号', '姓名', '成绩','评语','用时'],
      }
    ]
    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  }


  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '学号',
      dataIndex: 'student_number',
      key: 'age',
    },
    {
      title: '成绩',
      dataIndex: 'experiment_result',
      key: 'age',
    },

    {
      title: '用时',
      dataIndex: 'exam_time',
      key: 'age',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'age',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      key: 'age',
    },
    {
      title: '完成状态',
      dataIndex: 'complete_status',
      key: 'age',
      render: val => val===1?'已完成':'未参加',

    },
    {
      title: '附件',
      dataIndex: 'attachment_path',
      key: 'age',
      render: val => val?'已上传':'未上传',

    },
    {
      title: '评语',
      dataIndex: 'teacher_comment',
      key: 'age',
      render: val => val?'已点评':'未点评',

    },

    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => {setgradeVisible(true);setgradeCurrent(record.id)}}>成绩查询</a>
        </Space>
      ),
    },
  ];
  return (
    <Modal
    width={700}
      destroyOnClose
      title="考试成员管理"
      visible={modalVisible}
      onCancel={() => onCancel()}
    >
      <Descriptions title="">
       <Descriptions.Item label="考试名称">{grade.exam_name}</Descriptions.Item>
        <Descriptions.Item label="选择实验" span={1}>{grade.experiment_name}</Descriptions.Item>
        <Descriptions.Item label="考试说明">{grade.remark}</Descriptions.Item>
        <Descriptions.Item label="开始时间" span={1}>{grade.start_time}</Descriptions.Item>
        <Descriptions.Item label="结束时间" span={1}>{grade.end_time}</Descriptions.Item>
        <Descriptions.Item label="考试时长" span={1}>{grade.exam_time}</Descriptions.Item>
        {/* //有可能一个班级的人做的不同实验去掉 */}
        {/* <Descriptions.Item label="选择实验" span={1}>{grade.teacher_name}</Descriptions.Item>
        <Descriptions.Item label="考试说明" span={1}>{grade.teacher_name}</Descriptions.Item> */}
        <Descriptions.Item label="">
        
        <Grade
             currentinfo={gradeCurrent}
             onCancel={() => setgradeVisible(false)}
             modalVisible={gradeVisible}
          />
          <Modal
            title="请输入姓名/学号："
            visible={createModalVisible}
            onOk={()=>{addstu()}}
            onCancel={() => hideModal(false)}
            okText="添加"
            cancelText="取消"
          >
            <div>
            <Select
                  showSearch
                  // defaultValue={current ? current.admin_id : '1'}
                  value={classvalue}
                  placeholder="Select users"
                  notFoundContent={classfetch ? <Spin size="small" /> : null}
                  filterOption={false}
                  onSearch={fetchUser}
                  onChange={handleChange}
                  style={{ width: '100%' }}
                >
                  {teachdata.map(d => (
                    <Option key={d.id} value={d.id}>{d.name}</Option>
                  ))}
                </Select>
            </div>
          </Modal>
          
          <Divider type="vertical" />
          <Button type="primary" size='small' onClick={()=>{ExportToExcel()}}>
            导出
      </Button>
        </Descriptions.Item>

      </Descriptions>
      <Table rowSelection={rowSelection} columns={columns} dataSource={stulist}  pagination={paginationProps} rowKey={record => record.id}/>
    </Modal>
  );
};

export default Personinfo;
